<template>
  <div class="bucket-board-container">
    <div class="board-header">
      <div class="header-left">
        <div class="filter-dropdown">
          <el-dropdown @command="handleGroupByChange">
            <el-button type="primary" plain>
              <span>{{ t('bucketBoard.groupBy') }}: {{ groupByModeLabel }}</span>
              <el-icon class="el-icon--right"><arrow-down /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item :command="'bucket'" :class="{ active: groupByMode === 'bucket' }">{{ t('table.bucket')
                  }}</el-dropdown-item>
                <el-dropdown-item :command="'tag'" :class="{ active: groupByMode === 'tag' }">{{ t('cardEditor.tags')
                  }}</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
        <div class="search-container">
          <el-input v-model="searchKeyword" :placeholder="t('homepage.searchPlaceholder')" prefix-icon="Search"
            clearable @clear="handleSearch" @input="handleSearchInput" />
        </div>
      </div>
      <div class="header-right">
        <!-- 分页工具栏 -->
        <div class="pagination-container" v-if="allCards.length > 0">
          <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="pageSizeOptions"
            :layout="paginationLayout" :total="total" :total-text="t('table.total', { total: total })"
            :page-size-label="t('table.itemsPerPage')" :goto-label="t('table.gotoPage')" :page-label="t('table.page')"
            @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>

    <div v-loading="loading" class="bucket-columns-container">
      <!-- 无数据时显示空状态 -->
      <el-empty v-if="!loading && (!groupedCards || Object.keys(groupedCards).length === 0)"
        :description="t('table.noData')" />

      <!-- 分组展示 - 使用列布局 -->
      <div v-else class="bucket-columns">
        <!-- 分组卡片 -->
        <div v-for="(cards, groupName) in groupedCards" :key="groupName" class="bucket-column">
          <div class="bucket-column-header">
            <h3 class="bucket-title-text">{{ formatGroupTitle(groupName) }}</h3>
            <span class="card-count">{{ cards.length }}</span>
          </div>
          <div class="card-list">
            <div v-for="card in cards" :key="card.id" class="card-item" @click="viewCard(card)">
              <div class="card-header">
                <div class="card-icon">
                  <el-icon>
                    <Document />
                  </el-icon>
                </div>
                <div class="card-title">{{ card.title || t('cardEditor.untitledDoc') }}</div>
                <div class="card-actions">
                  <el-dropdown trigger="click" @command="handleCommand($event, card)" @click.stop>
                    <span class="el-dropdown-link">
                      <el-icon>
                        <More />
                      </el-icon>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item command="edit">{{ t('common.edit') }}</el-dropdown-item>
                        <el-dropdown-item command="delete" divided>{{ t('common.delete') }}</el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </div>
              <div class="card-info">
                <div class="card-tags" v-if="card.tags && card.tags.length">
                  <el-tag v-for="tag in card.tags.slice(0, 2)" :key="tag" size="small" class="tag-item" :style="card.tagColors && card.tagColors[tag] ?
                    { backgroundColor: card.tagColors[tag] + '33', borderColor: card.tagColors[tag], color: card.tagColors[tag] } :
                    {}">
                    {{ tag }}
                  </el-tag>
                  <span v-if="card.tags.length > 2" class="more-tags">+{{ card.tags.length - 2 }}</span>
                </div>
                <div class="card-meta">
                  <el-avatar size="small" v-if="(card as any).avatar">{{ (card as any).avatar }}</el-avatar>

                  <span class="update-time">{{ formatDateTime(card.updated) }}</span>
                </div>
              </div>
            </div>
            <div class="add-card">
              <el-button v-if="groupByMode === 'bucket'" link @click="quickCreateCard(groupName)">+ {{
                t('bucketBoard.addToBucket') }}</el-button>
              <el-button v-else-if="groupByMode === 'tag' && groupName !== ''" link
                @click="quickCreateCardWithTag(groupName)">+ {{ t('bucketBoard.addWithTag') }}</el-button>
              <el-button v-else link @click="quickCreateCard('')">+ {{ t('homepage.createCard') }}</el-button>
            </div>
          </div>
        </div>

        <!-- 新增桶/标签列 -->
        <div class="bucket-column add-bucket-column">
          <div class="add-bucket-button">
            <el-button link @click="addNewCategory">+ {{ groupByMode === 'bucket' ? t('settings.addBucket') :
              t('bucketBoard.addTagGroup') }}</el-button>
          </div>
        </div>
      </div>
    </div>


  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { ElMessageBox, ElMessage } from 'element-plus';
import { Plus, More, Document, ArrowDown } from '@element-plus/icons-vue';
import { format } from 'date-fns';
import { zhCN, enUS } from 'date-fns/locale';
import { fetchCards, deleteCard as deleteCardApi } from '../services/cardService';
import type { CardItem } from '../types/cardData';
import { setSourcePage } from '../utils/navigation';

const { t, locale } = useI18n();
const router = useRouter();
const loading = ref(true);
const allCards = ref<CardItem[]>([]);
const searchKeyword = ref('');
const searchTimeout = ref<number | null>(null);
const groupByMode = ref<'bucket' | 'tag'>('bucket'); // 默认按桶名称分组

// 获取用户配置的页面大小
const getUserPageSize = (): number => {
  try {
    const generalSettings = localStorage.getItem('general-settings');
    if (generalSettings) {
      const settings = JSON.parse(generalSettings);
      if (settings.pageSize && typeof settings.pageSize === 'number') {
        return settings.pageSize;
      }
    }
  } catch (error) {
    console.error('获取页面大小设置失败:', error);
  }
  return 15; // 默认值
};

// 获取页面大小选项
const getPageSizeOptions = (): number[] => {
  try {
    const generalSettings = localStorage.getItem('general-settings');
    if (generalSettings) {
      const settings = JSON.parse(generalSettings);
      if (settings.pageSizeOptions && Array.isArray(settings.pageSizeOptions) && settings.pageSizeOptions.length > 0) {
        return settings.pageSizeOptions;
      }
    }
  } catch (error) {
    console.error('获取页面大小选项设置失败:', error);
  }
  return [10, 15, 20, 50]; // 默认值
};

// 添加分页相关变量
const currentPage = ref(1);
const pageSize = ref(getUserPageSize()); // 从用户配置获取默认大小
const pageSizeOptions = ref(getPageSizeOptions()); // 从用户配置获取可选大小列表
const total = ref(0);
const paginationLayout = 'sizes, prev, pager, next, total';

// 分组方式标签
const groupByModeLabel = computed(() => {
  return groupByMode.value === 'bucket'
    ? t('table.bucket')
    : t('cardEditor.tags');
});

// 过滤后的卡片
const filteredCards = computed(() => {
  if (!allCards.value.length) return [];

  // 如果有搜索关键词，过滤卡片
  return searchKeyword.value ?
    allCards.value.filter(card =>
      (card.title && card.title.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
      (card.content && card.content.toLowerCase().includes(searchKeyword.value.toLowerCase())) ||
      (card.tags && card.tags.some(tag => tag.toLowerCase().includes(searchKeyword.value.toLowerCase())))
    ) :
    allCards.value;
});

// 当前页的卡片数据
const currentPageCards = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredCards.value.slice(start, end);
});

// 分组后的卡片数据
const groupedCards = computed(() => {
  if (!currentPageCards.value.length) return {};

  if (groupByMode.value === 'bucket') {
    // 按桶分组
    return currentPageCards.value.reduce((groups: Record<string, CardItem[]>, card) => {
      const bucketName = card.bucket || '';
      if (!groups[bucketName]) {
        groups[bucketName] = [];
      }
      groups[bucketName].push(card);
      return groups;
    }, {});
  } else {
    // 按标签分组
    const groups: Record<string, CardItem[]> = {};
    // 首先创建一个未分类组
    groups[''] = [];

    currentPageCards.value.forEach(card => {
      if (!card.tags || card.tags.length === 0) {
        // 没有标签的卡片放入未分类组
        groups[''].push(card);
      } else {
        // 有标签的卡片，为每个标签创建一个分组并添加卡片
        card.tags.forEach(tag => {
          if (!groups[tag]) {
            groups[tag] = [];
          }
          groups[tag].push(card);
        });
      }
    });

    // 如果未分类组为空，则删除该组
    if (groups[''].length === 0) {
      delete groups[''];
    }

    return groups;
  }
});

// 格式化分组标题
const formatGroupTitle = (groupName: string) => {
  if (groupName === '') {
    return t('bucketBoard.uncategorized');
  }
  return groupName;
};

// 处理分组方式变更
const handleGroupByChange = (command: string) => {
  if (command === 'bucket' || command === 'tag') {
    groupByMode.value = command as 'bucket' | 'tag';
  }
};

// 检查设置是否变化
const checkForSettingsChanges = () => {
  // 检查页面大小设置是否变化
  const newPageSize = getUserPageSize();
  const newPageSizeOptions = getPageSizeOptions();
  
  let needReload = false;
  
  // 检查页面大小是否变化
  if (newPageSize !== pageSize.value) {
    console.log('检测到页面大小设置变化:', pageSize.value, '->', newPageSize);
    pageSize.value = newPageSize;
    needReload = true;
  }
  
  // 检查页面大小选项是否变化
  if (JSON.stringify(newPageSizeOptions) !== JSON.stringify(pageSizeOptions.value)) {
    console.log('检测到页面大小选项设置变化');
    pageSizeOptions.value = newPageSizeOptions;
  }
  
  // 如果设置变化，需要重新计算分页
  if (needReload) {
    // 更新total
    total.value = filteredCards.value.length;
  }
};

// 加载卡片数据
const loadCards = async () => {
  loading.value = true;
  try {
    // 设置用户配置的页面大小
    pageSize.value = getUserPageSize();

    // 获取所有卡片数据
    const response = await fetchCards(1, 1000);
    allCards.value = response.items;
    total.value = response.total;

    // 设置窗口焦点监听，检测设置变化
    window.addEventListener('focus', checkForSettingsChanges);
  } catch (error) {
    console.error('Failed to load cards:', error);
    ElMessage.error(t('common.loadFailed'));
  } finally {
    loading.value = false;
  }
};

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return '';

  try {
    const date = new Date(dateStr);
    return format(date, 'MM-dd', {
      locale: locale.value === 'zh-CN' ? zhCN : enUS
    });
  } catch (e) {
    return dateStr;
  }
};

// 查看卡片详情
const viewCard = (card: CardItem) => {
  setSourcePage('BucketBoard');
  router.push({ name: 'ViewCard', params: { id: card.id } });
};

// 创建新卡片
const createNewCard = () => {
  setSourcePage('BucketBoard');
  router.push({ name: 'CardEditor' });
};

// 直接创建空白卡片到指定桶
const quickCreateCard = async (bucketName: string) => {
  loading.value = true;
  try {
    // 获取当前时间，使用应用的时间格式工具
    const now = await window.electronAPI.getCurrentDateTime();
    
    // 创建一个空白卡片对象
    const newCard: Partial<CardItem> = {
      title: t('cardEditor.untitledDoc'),
      content: '',
      markdown: '',
      bucket: bucketName,
      tags: [],
      created: now,
      updated: now,
      startTime: now
    };

    // 调用保存API
    const savedCard = await window.electronAPI.saveCard(newCard);

    // 重新加载卡片列表
    await loadCards();

    // 显示成功消息
    ElMessage.success(t('common.createSuccess'));
  } catch (error) {
    console.error('Failed to create card:', error);
    ElMessage.error(t('common.createFailed'));
  } finally {
    loading.value = false;
  }
};

// 直接创建带有特定标签的空白卡片
const quickCreateCardWithTag = async (tagName: string) => {
  if (tagName === '') return; // 不处理空标签

  loading.value = true;
  try {
    // 获取当前时间，使用应用的时间格式工具
    const now = await window.electronAPI.getCurrentDateTime();
    
    // 创建一个空白卡片对象，带有指定标签
    const newCard: Partial<CardItem> = {
      title: t('cardEditor.untitledDoc'),
      content: '',
      markdown: '',
      bucket: '',
      tags: [tagName],
      created: now,
      updated: now,
      startTime: now
    };

    // 调用保存API
    const savedCard = await window.electronAPI.saveCard(newCard);

    // 重新加载卡片列表
    await loadCards();

    // 显示成功消息
    ElMessage.success(t('common.createSuccess'));
  } catch (error) {
    console.error('Failed to create card:', error);
    ElMessage.error(t('common.createFailed'));
  } finally {
    loading.value = false;
  }
};

// 编辑卡片
const editCard = (card: CardItem) => {
  setSourcePage('BucketBoard');
  router.push({ name: 'EditCard', params: { id: card.id } });
};

// 删除卡片
const deleteCard = async (card: CardItem) => {
  try {
    await ElMessageBox.confirm(
      t('common.deleteConfirmText'),
      t('common.warning'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        type: 'warning',
      }
    );

    const success = await deleteCardApi(card.id);
    if (success) {
      ElMessage.success(t('common.deleteSuccess'));
      // 重新加载卡片列表
      loadCards();
    } else {
      ElMessage.error(t('common.deleteFailed'));
    }
  } catch (e) {
    // 用户取消操作，不做处理
  }
};

// 下拉菜单命令处理
const handleCommand = (command: string, card: CardItem) => {
  if (command === 'edit') {
    editCard(card);
  } else if (command === 'delete') {
    deleteCard(card);
  }
};

// 搜索处理
const handleSearch = () => {
  // 清空搜索框时重新加载所有卡片
  if (!searchKeyword.value) {
    loadCards();
  }
  // 重置分页到第一页
  currentPage.value = 1;
};

// 搜索输入处理（防抖）
const handleSearchInput = () => {
  if (searchTimeout.value) {
    clearTimeout(searchTimeout.value);
  }

  searchTimeout.value = window.setTimeout(() => {
    handleSearch();
    searchTimeout.value = null;
  }, 300);
};

// 处理分页大小变化
const handleSizeChange = (val: number) => {
  pageSize.value = val;
};

// 处理当前页变化
const handleCurrentChange = (val: number) => {
  currentPage.value = val;
};

// 添加新分类（桶或标签）
const addNewCategory = () => {
  if (groupByMode.value === 'bucket') {
    // 添加新桶
    ElMessageBox.prompt(
      t('settings.bucketNamePlaceholder'),
      t('settings.addBucket'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        inputPattern: /.+/, // 非空内容
        inputErrorMessage: t('settings.bucketNameEmpty')
      }
    ).then(({ value }) => {
      // 创建一个带有新桶的空白卡片
      quickCreateCard(value);
    }).catch(() => {
      // 用户取消操作，不做处理
    });
  } else {
    // 添加新标签
    ElMessageBox.prompt(
      t('cardEditor.addTag'),
      t('bucketBoard.addTagGroup'),
      {
        confirmButtonText: t('common.confirm'),
        cancelButtonText: t('common.cancel'),
        inputPattern: /.+/, // 非空内容
        inputErrorMessage: t('settings.bucketNameEmpty')
      }
    ).then(({ value }) => {
      // 创建一个带有新标签的空白卡片
      quickCreateCardWithTag(value);
    }).catch(() => {
      // 用户取消操作，不做处理
    });
  }
};

// 页面加载时获取数据
onMounted(() => {
  loadCards();
});

// 组件卸载时清理
onBeforeUnmount(() => {
  // 移除窗口焦点监听
  window.removeEventListener('focus', checkForSettingsChanges);
});
</script>

<style scoped>
.bucket-board-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 12px;
  overflow: hidden;
  box-sizing: border-box;
}

.board-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  flex-shrink: 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-right {
  display: flex;
  align-items: center;
  flex-shrink: 0;
}

.search-container {
  width: 200px;
}

.bucket-columns-container {
  flex: 1;
  overflow-x: auto;
  overflow-y: hidden;
  padding-bottom: 0;
  margin-bottom: 0;
  min-height: 0; /* 关键属性，解决flex布局中的溢出问题 */
}

.bucket-columns {
  display: flex;
  height: 100%;
  gap: 12px;
  min-height: 0;
}

.bucket-column {
  min-width: 270px;
  width: 270px;
  height: 100%;
  max-height: 100%;
  background-color: #f7f8fa;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  flex-shrink: 0;
  overflow: hidden;
}

.bucket-column-header {
  display: flex;
  align-items: center;
  padding: 10px 12px;
  border-bottom: 1px solid #ebeef5;
  flex-shrink: 0;
}

.bucket-column-header h3 {
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #303133;
  flex: 1;
}

.bucket-title-text {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 200px;
}

.card-count {
  background-color: #f2f6fc;
  color: #909399;
  border-radius: 10px;
  padding: 1px 6px;
  font-size: 12px;
  margin-left: 6px;
}

.card-list {
  flex: 1;
  overflow-y: auto;
  padding: 6px;
  display: flex;
  flex-direction: column;
  gap: 6px;
  max-height: calc(100% - 50px);
  /* 减去标题栏高度 */
}

.card-item {
  background-color: white;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  padding: 10px;
  cursor: pointer;
  transition: box-shadow 0.2s;
  flex-shrink: 0;
}

.card-item:hover {
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: flex-start;
  margin-bottom: 10px;
}

.card-icon {
  color: #909399;
  margin-right: 8px;
  margin-top: 2px;
}

.card-title {
  font-size: 14px;
  line-height: 1.4;
  color: #303133;
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.card-actions {
  margin-left: 8px;
}

.el-dropdown-link {
  cursor: pointer;
  display: flex;
  align-items: center;
  color: #909399;
}

.card-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.card-tags {
  display: flex;
  gap: 4px;
  flex-wrap: wrap;
}

.tag-item {
  max-width: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.more-tags {
  color: #909399;
  font-size: 12px;
}

.card-meta {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.update-time {
  font-size: 12px;
}

.add-card {
  margin-top: 4px;
  text-align: center;
  padding: 4px 0;
  flex-shrink: 0;
}

.add-bucket-column {
  min-width: 270px;
  width: 270px;
  background-color: transparent;
  border: 2px dashed #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: center;
}

.add-bucket-button {
  color: #909399;
  cursor: pointer;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 下拉菜单激活项样式 */
.el-dropdown-menu__item.active {
  color: #409EFF;
  font-weight: bold;
}

/* 分页容器样式 */
.pagination-container {
  flex-shrink: 0;
  display: flex;
  justify-content: flex-end;
  padding: 0;
  margin: 0 0 0 16px;
}

/* 调整el-pagination组件样式使其更紧凑 */
:deep(.el-pagination) {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  font-size: 12px;
}

:deep(.el-pagination .el-input__inner) {
  height: 28px;
  line-height: 28px;
  font-size: 12px;
}

:deep(.el-pagination .el-select .el-input) {
  width: 80px;
}

:deep(.el-pagination button) {
  min-width: 28px;
  height: 28px;
}

:deep(.el-pagination .el-pager li) {
  min-width: 28px;
  height: 28px;
  line-height: 28px;
}
</style>